<template>
  <div>
    <NuxtLayout name="default">
      <template #tools>
        <Tools :active="toolsVal" @change="toolsChange" />
      </template>
      <template v-if="toolsVal <= 1" #panel>
        <!-- <TheMultiple  @to="toolsVal = 2" v-if="toolsVal === 0" />
        <TheSession v-if="toolsVal === 1" /> -->
        <component
          @to="toolsVal = 2"
          :is="chattingMode[toolsVal].panel"
        ></component>
      </template>

      <template v-if="toolsVal <= 1">
        <div class="h-full flex">
          <Chatting
            ref="chattingRef"
            v-model:chat="chatParams.chatKey"
            v-model:model="chatParams.modelKey"
            v-model:network="chatParams.network"
            :content-list="chatContentList"
            :send-disabled="isReceiving"
            :selectval="sessionActive"
            :avatar="appStore.config.chat.chatLogo"
            :chat-type="1"
            @close="chatClose"
            @update="getChatList"
            @content-post="contentPost"
            @clean-chat-log="cleanChatLog"
          >
            <div
              v-if="!chatContentList.length"
              style="position: absolute"
              class="w-full h-[100%] flex flex-col justify-end px-[50px] left-[0px]"
            >
              <!-- <div
                            class="my-[60px] text-center text-[30px] font-medium"
                        >
                            {{ appStore.getChatConfig.chatTitle }}
                        </div> -->
              <div class="mb-[190px]" style="height: calc(50% - 160px)">
                <ChattingIcon></ChattingIcon>
              </div>
              <div class="flex">
                <div
                  v-for="item in exampleList.slice(0, 3)"
                  :key="item.id"
                  class="flex-1 mx-[10px]"
                >
                  <div>
                    <div
                      v-for="sample in item.sampleList"
                      :key="sample.id"
                      class="sample-item mb-[20px] p-[10px] flex justify-center cursor-pointer"
                      @click="contentPost(sample.content)"
                    >
                      <div class="line-clamp-2">
                        {{ sample.content }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Chatting>
        </div>
        <TheGuidedPopup ref="guidedPopupRef" />
      </template>

      <template v-if="toolsVal === 2">
        <Create />
      </template>
      <template v-if="toolsVal === 3">
        <Aides />
      </template>
      <!-- <component :is="chattingMode[toolsVal].default"></component> -->
    </NuxtLayout>
  </div>
</template>
<script setup lang="ts">
import Aides from "./aides/index.vue";
import { getchatLog, samplesLists, cleanChat, chatSendText } from "@/api/chat";
import { useUserStore } from "~~/stores/user";
import ChattingIcon from "@/components/chatting/icon.vue";
import feedback from "~~/utils/feedback";
import { ElMessageBox } from "element-plus";
import { useAppStore } from "~/stores/app";
import Tools from "@/layouts/components/tools/index.vue";
import Create from "~~/pages/create/index.vue";
import TheMultiple from "@/components/the-multiple/index.vue";
import TheSession from "@/components/the-session/index.vue";
import { useSessionList } from "@/composables/useSessionList";

const { lockFn: sessionAddLock, isLock } = useLockFn(async () => {
  await sessionAdd();
});
const chattingMode = ref([
  {
    panel: markRaw(TheMultiple),
    default: null,
  },
  {
    panel: markRaw(TheSession),
    default: null,
  },
  {
    panel: null,
    default: markRaw(Create),
  },
  {
    panel: null,
    default: markRaw(Aides),
  },
]);
const userStore = useUserStore();
const appStore = useAppStore();
const router = useRouter();
const route = useRoute();
//对话记录列表

//对话框ref
const chattingRef = ref(null);
const guidedPopupRef = shallowRef();
const chatParams = reactive({
  chatKey: "",
  modelKey: "",
  network: false,
});
const {
  sessionActive,
  sessionAdd,
  currentSession,
  sessionEdit,
  getSessionLists,
} = await useSessionList();

const toolsVal = ref<any>(0);

await useAsyncData(() => getSessionLists(), {
  default() {
    return [];
  },
  immediate: true,
});
//问题示例列表
const { data: exampleList } = await useAsyncData(() =>
  samplesLists({ type: 1 })
);
const toolsChange = (value: number) => {
  toolsVal.value = value;
  router.push({
    path: "/app/chatting",
    query: {
      id: value,
    },
  });
  // console.log(route.query.id = toolsVal.value)
  
  // if (id === 0 && chatContentList.value.length) {
  //   console.log(id, "1111", chatContentList.value);
  //   const currentTime: any = new Date();
  //   // 指定时间
  //   const targetTime: any = new Date(
  //     chatContentList.value[chatContentList.value.length - 1].createTime
  //   );

  //   // 计算时间差（以毫秒为单位）
  //   const hoursDifference = (targetTime - currentTime) / (1000 * 60 * 60);

  //   // 判断是否超过24小时
  //   if (hoursDifference > 24) {
  //     console.log("超过24小时");
  //     sessionAddLock();
  //     appStore.getChatConfig.is_reopen = 0;
  //   }
  // }
};

const actions = ref<string>("");
//获取聊天记录
const { data: chatContentList, refresh: getChatList } = await useAsyncData(
  () =>
    getchatLog({
      type: 1,
      categoryId: sessionActive.value,
      action: actions.value,
    }),
  {
    transform(data) {
      return data.map((item: any) => {
        if (item.type == 1) {
          return { ...item, fromAvatar: userStore.userInfo.avatar };
        } else {
          return {
            ...item,
            fromAvatar: appStore.config.chat.chatLogo,
          };
        }
      });
    },
    default() {
      return [];
    },
  }
);
const { pauseAll } = useAudioPlay();
const isReceiving = ref(false);
const newUserInput = ref<string>("");
//发送问题
const contentPost = async (userInput: any) => {
  if (!userStore.isLogin) return userStore.toggleShowLogin(true);
  if (isReceiving.value) return;
  if (sessionActive.value === 0) {
    await sessionAdd();
  }
  if (currentSession.value === "新的会话") {
    await sessionEdit(sessionActive.value, userInput);
  }
  chatContentList.value.push({
    type: 1,
    content: userInput,
    fromAvatar: userStore.userInfo.avatar,
  });
  chatContentList.value.push({
    type: 2,
    loading: true,
    content: [],
    fromAvatar: appStore.config.chat.chatLogo,
    id: "",
  });
  isReceiving.value = true;
  try {
    await chatSendText(
      {
        question: userInput,
        type: 1,
        categoryId: sessionActive.value,
        ...chatParams,
      },
      {
        onstart(reader) {
          streamReader = reader;
          pauseAll();
        },
        onmessage(value) {
          value
            .trim()
            .split("data:")
            .forEach(async (text) => {
              if (text !== "") {
                try {
                  const dataJson = JSON.parse(text);
                  const { id: chatId, event, data, index, error } = dataJson;

                  console.log(dataJson);

                  if (error && error.errCode === 101) {
                    guidedPopupRef.value?.open();
                    return;
                  } else if (error) {
                    feedback.msgError(error.errMsg);
                    return;
                  }

                  let chatIndex = chatContentList.value.findIndex(
                    (item) => item.id === chatId
                  );
                  if (chatIndex === -1) {
                    chatIndex = chatContentList.value.length - 1;

                    chatContentList.value[chatIndex].id = chatId;
                  }

                  if (data) {
                    if (!chatContentList.value[chatIndex].content[index]) {
                      chatContentList.value[chatIndex].content[index] = "";
                    }
                    chatContentList.value[chatIndex].content[index] += data;
                  }

                  if (event === "finish") {
                    chatContentList.value[chatIndex].loading = false;
                    return;
                  }
                } catch (error) {}
              }
            });
        },
        onclose() {
          isReceiving.value = false;
          setTimeout(getChatList, 0);
          userStore.getUser();
        },
      }
    );
    chattingRef.value.cleanInput();
  } catch (error) {
    isReceiving.value = false;
    chatContentList.value.splice(chatContentList.value.length - 2, 2);
  }

  nextTick(() => {
    chattingRef.value.scrollToBottom();
  });
};

let streamReader: ReadableStreamDefaultReader<Uint8Array> | null = null;
const chatClose = (index?: number) => {
  actions.value = "stop";
  streamReader?.cancel();
  if (index) {
    chatContentList.value[index].loading = false;
  }
  isReceiving.value = false;
};

//清空会话
const cleanChatLog = async () => {
  await feedback.confirm("确定清空对话？");
  await cleanChat({ type: 1, categoryId: sessionActive.value });
  chatContentList.value = [];
};

onMounted(async () => {
  toolsVal.value = Number(route.query.id) || 0
  if (route.query.cid || route.query.user_sn) {
    const cid: any = useCookie("cid");
    const user_sn: any = useCookie("user_sn");
    cid.value = route.query.cid;
    user_sn.value = route.query.user_sn;
    await nextTick();
    userStore.checkShare();
  }
  await nextTick();
  chattingRef.value.scrollToBottom();
});
watch(sessionActive, async () => {
  chatClose();
  actions.value = "";
  await getChatList();
  await nextTick();
  chattingRef.value.scrollToBottom();
});

definePageMeta({
  layout: false,
});
</script>
<style lang="scss" scoped>
.container-tip {
  border: 1px solid #fb9a3b;
}
.item {
  :hover {
    color: #fb9a3b;
  }
}
.sample-item {
  border-radius: 12px;
  background: #363a46;
  color: var(--color-text-base);
  // border: 1px solid #eef2f2;
  // box-shadow: 0 2px 8px #f5f6f8;
}
</style>
